<template>
  <!-- 顶部自定义 -->
  <title-mobile :titleShow="true" :gradient="false">
    <div class="title-mobile-container">
      <div class="head" @click="toUserInfo(user.id)">
        <el-avatar :size="34" :src="user.headImage" />
      </div>
      <div class="username" @click="toUserInfo(user.id)">{{user.nickName}}</div>
      <div class="guanzhu"> &nbsp;&nbsp;<span class="tulin tulin-more"
          @click="moreOption = true"></span>&nbsp;
      </div>
      <div class="share" v-show="user.id!=mineId">
        <el-button v-if="!isFan" class="share-btn" type="danger" size="small" @click="addFan">关注
        </el-button>
        <el-button v-if="isFan" class="share-btn" type="info" size="small" plain @click="deleteFan">
          <el-icon><Select /></el-icon>已关注
        </el-button>
      </div>

      <ShareSheet v-model:show="showShare" title="立即分享给好友" :options="shareOptions"
        @select="onShareSelect" />

      <ShareSheet v-model:show="moreOption" title="更多操作" :options="moreOptions"
        @select="onMoreOption" />
    </div>
  </title-mobile>
  <div class="container">
    <div class="my-swipe">
      <!-- 轮播图 -->
      <Swipe class="my-swipe-inner" indicator-color="white" @change="swipeChange" :loop="true"
        ref="swipe" @click="showPreview">
        <SwipeItem v-for="img in imgList" :key="img">
          <div class="image">
            <el-image style="width: 100%; height: 100%" :src="minioUrl+img.oosKey" fit="scale-down">
              <template #error>
                <div class="image-slot">
                  加载中...
                </div>
              </template>
            </el-image>
          </div>
        </SwipeItem>
        <template #indicator>
          <div class="custom-indicator">{{ currentImg + 1 }}/{{imgList.length}}</div>
        </template>
      </Swipe>
    </div>
    <div class="center">
      <!-- 轮播图索引 -->
      <div class="swipe-index">
        <div v-for="index in imgList.length" :key="index" ref="swipeIndex">
        </div>
      </div>
      <!-- 标题 -->
      <div class="works-title">
        {{works.title}}
      </div>
      <div class="row-line"></div>
      <!-- 内容 -->
      <div class="works-description">
        <el-input type="textarea" v-model="works.description" size="large" maxlength="1000" readonly
          :autosize="{ minRows: 1, maxRows: 100 }">
        </el-input>
      </div>
      <div class="row-line"></div>
      <!-- 标签 -->
      <div class="works-tag">
        <span v-for="item in worksTags" :key="item.id">
          #{{item.name}}
        </span>
      </div>
      <!-- 时间地址 -->
      <div class="works-time">
        <span>{{works.createTime}}</span>
        <span> IP:{{placeName}}</span>
      </div>

      <!-- 评论 -->
      <div class="works-comment">
        <div>共有{{likeFormat1(commentCount)}}条评论</div>
        <div class="row-line"></div>
        <!-- 发言 -->
        <div class="commnet-text">
          <el-row>
            <el-col :xs="4" :sm="3" :md="1" :lg="1" :xl="1">
              <el-avatar :size="40" :src="mineHeadImage" />
            </el-col>
            <el-col :xs="20" :sm="21" :md="23" :lg="23" :xl="23">
              <el-input v-model="currentContent" @keyup.enter="addComment" placeholder="文明发言你我他~"
                size="default" maxlength="255">
                <template #append>
                  <div @click="addComment">发送</div>
                </template>
              </el-input>
            </el-col>
          </el-row>
        </div>
        <!-- 评论信息列表 -->
        <div class="comment-list" v-infinite-scroll="getRootComments" infinite-scroll-delay="200"
          :infinite-scroll-disabled="rootCommentMore">
          <!-- 父评论 -->
          <el-row v-for="comment in commentList" :key="comment.id">
            <el-col :xs="3" :sm="3" :md="1" :lg="1" :xl="1" @click="toUserInfo(comment.userId)">
              <el-avatar :size="40" fit="cover" :src="comment.headImage" />
            </el-col>
            <el-col :xs="21" :sm="21" :md="23" :lg="23" :xl="23">
              <div>{{comment.userId==mineId?'我':comment.nickName}}</div>
              <div style="word-wrap: break-word;">{{comment.content}}</div>
              <div class="comment-time">{{dateFormat1(comment.createTime)}}
                <span style="color:#7171c1" v-show="comment.userId!=mineId"
                  @click="dialogInput(comment,comment)">回复</span>
              </div>
              <!-- 子评论 -->
              <el-row v-for="child in comment.childComment" :key="child.id">
                <el-col :xs="3" :sm="3" :md="1" :lg="1" :xl="1" @click="toUserInfo(child.userId)">
                  <el-avatar :size="30" fit="cover" :src="child.headImage" />
                </el-col>
                <el-col style="font-size:14px" :xs="21" :sm="21" :md="23" :lg="23" :xl="23">
                  <!-- 子评论用户名称及回复 -->
                  <div>
                    <span>{{child.userId==mineId?'我':child.nickName}}</span>
                    <span style="color:#7171c1" v-if="child.parentNickName!=comment.nickName">
                      @{{child.parentUserId==mineId?'我':child.parentNickName}}</span>
                  </div>
                  <!-- 子评论内容 -->
                  <div style="word-wrap: break-word;"> {{child.content}}</div>
                  <div class="comment-time">{{dateFormat1(child.createTime)}}
                    <span style="color:#7171c1" v-show="child.userId!=mineId"
                      @click="dialogInput(child,comment)">回复</span>
                  </div>
                  <div style="margin-bottom:5px"></div>
                </el-col>
              </el-row>
              <div class="child-more" v-show="comment.isMoreChild"
                @click="getLevelComments(comment)">展开更多回复>></div>
              <div class="commnet-line"></div>
            </el-col>
          </el-row>
          <div class="no-more" v-show="rootCommentMore">没有更多啦~</div>
        </div>
      </div>
    </div>
  </div>
  <!-- 底部 -->
  <div class="bottom">

    <div class="bottom-like">
      <span v-bind:class="['tulin',{'tulin-like':like.isLike}]" @click="cancelLike(worksId)" />
      <span v-bind:class="['tulin',{'tulin-unlike':!like.isLike}]" @click="likeClike(worksId)" />
      <span class="bottom-like-text">{{likeFormat1(like.likeCount)}}</span>
    </div>

    <div class="bottom-collection">
      <span v-bind:class="['tulin',{'tulin-uncollection':!collection.isWorksCollection}]"
        @click="addCollection"></span>
      <span v-bind:class="['tulin',{'tulin-collection':collection.isWorksCollection}]"
        @click="addCollection"></span>
      <span class="bottom-like-text">{{likeFormat1(collection.count)}}</span>
    </div>

    <div class="bottom-input">
      <el-input v-model="currentContent" @keyup.enter="addComment" placeholder="文明发言你我他~"
        maxlength="255">
      </el-input>
    </div>
    <input style="position: fixed;left:10000000px" type="text" id="copylink">
  </div>
</template>

<script>
import { Swipe, SwipeItem, ImagePreview, ShareSheet } from 'vant';
import { dateFormat, likeFormat, userId, headImage, copyText } from '../../utils/index';
import { minioUrl } from "../../base/index";
import { ElMessage, ElMessageBox } from 'element-plus';
import jubaoImage from "@/assets/imge/inco/jubao.png";
import deleteImage from "@/assets/imge/inco/delete.png";
export default {
  name: "GShow",
  data () {
    return {
      mineId: userId,
      mineHeadImage: headImage,
      currentImg: 0,
      show: false,
      currentContent: "",
      showShare: false,
      moreOption: false,
      rootCommentMore: false,
      shareOptions: [
        [
          { name: '微信', icon: 'wechat' },
          { name: '朋友圈', icon: 'wechat-moments' },
          { name: '微博', icon: 'weibo' },
          { name: 'QQ', icon: 'qq' },
          { name: '复制链接', icon: 'link' },
          { name: '分享海报', icon: 'poster' },
          { name: '二维码', icon: 'qrcode' },
          { name: '小程序码', icon: 'weapp-qrcode' },
        ],
      ],
      moreOptions: [
        [
          { name: '举报', icon: jubaoImage },
          { name: '分享', icon: 'link' }
        ],
      ],
      isFan: false,
      worksId: {},
      user: {},
      works: {},
      worksTags: {},
      commentList: [],
      commentCount: 0,
      like: {
        likeCount: 0,
        isLike: false,
      },
      collection: {
        count: 0,
        isWorksCollection: false,
      },
      placeName: "",
      imgList: [
        {
          url: "",
          oosKey: ""
        },
      ],
      imgListPreView: [],
      rootCommentPageNum: 1,
      jubaoImage,
      deleteImage,
      minioUrl,
    };
  },
  components: {
    Swipe, SwipeItem, ShareSheet
  },
  mounted () {
    document.documentElement.scrollTop = 0;
    this.worksId = this.$route.params.worksId;
    this.loadWorks(this.worksId);
    this.isCollectionFun();
    this.getRootComments();
    this.getCommentsCount();
  },
  methods: {
    loadWorks (worksId) {
      //获取作品信息
      this.$axios.get("/works/" + worksId)
        .then(res => {
          if (res.flag) {
            this.works = res.data.works;
            this.works.createTime = dateFormat(this.works.createTime, 2);
            this.user = res.data.user;
            this.worksTags = res.data.worksTags;
            this.placeName = res.data.placeName;
            this.like.isLike = res.data.isLike;
            this.like.likeCount = res.data.likeCount;
            return res
          } else {
            this.$router.back();
          }
        }).then((res) => {
          //添加删除作品功能·
          this.addDeleteOption();
          //查看是否关注
          if (res.flag) {
            this.$axios.get("/fan/isfan/" + res.data.user.id).then((res) => {
              if (res.flag) {
                this.isFan = res.data;
              }
            })
          }
        })
      this.$axios.get("/works/img/" + worksId).then(res => {
        //获取作品图片信息
        if (res.flag) {
          this.imgList = res.data;
          this.swipeIndexChange(0);
          for (var key in this.imgList) {
            this.imgListPreView.push(this.imgList[key].url + this.imgList[key].oosKey);
          }
        }
      })
    },
    getRootComments () {
      this.$axios.get("/comment/root/" + this.worksId + "/" + (this.rootCommentPageNum++) + "/10").then(res => {
        if (res.flag) {
          if (res.data.length < 1) {
            this.rootCommentMore = true;
          }
          for (var key in res.data) {
            //子评论如果有更多
            if (res.data[key].childComment.length > 0) {
              res.data[key].isMoreChild = true;
              res.data[key].pageNum = 1;
              //前端第一次获取先隐藏子评论
              res.data[key].childComment = [];
            } else {
              res.data[key].isMoreChild = false;
            }
            this.commentList.push(res.data[key]);
          }
        }
      })
    },
    //获取二级评论
    getLevelComments (parentComment) {
      this.$axios.get("/comment/level/" + parentComment.id + "/" + (parentComment.pageNum++) + "/10").then(res => {
        if (res.flag) {
          //如果没有更多子评论，就隐藏查看更多按钮
          if (res.data.length < 1) {
            parentComment.isMoreChild = false;
          } else {
            //获取子评论加入
            for (var key in res.data) {
              parentComment.childComment.push(res.data[key]);
            }
          }
        }
      })
    },
    //添加根评论
    addComment () {
      if (this.currentContent == "") {
        ElMessage({
          message: "内容不能为空",
          // grouping: true,
          type: 'error',
          duration: 2000,
        })
        return;
      } else if (this.currentContent.length > 255) {
        ElMessage({
          message: "内容过长",
          type: 'error',
          duration: 2000,
        })
        return;
      }
      this.$axios.post("/comment", {
        worksId: this.worksId,
        content: this.currentContent
      }).then(res => {
        if (res.flag) {
          this.commentList.unshift({
            id: res.data.id,
            createTime: res.data.createTime,
            nickName: "我",
            userId: this.mineId,
            content: this.currentContent,
            headImage: this.mineHeadImage,
          })
          ElMessage({
            message: res.msg,
            grouping: true,
            type: 'success',
            duration: 2000,
          })
          this.commentCount += 1;
          this.currentContent = "";
        }
      })
    },
    //回复评论
    addChildComment (parent, rootComment) {
      if (this.currentContent == "") {
        ElMessage({
          message: "内容不能为空",
          // grouping: true,
          type: 'error',
          duration: 2000,
        })
        return;
      } else if (this.currentContent.length > 255) {
        ElMessage({
          message: "内容过长",
          type: 'error',
          duration: 2000,
        })
        return;
      }
      this.$axios.post("/comment", {
        worksId: this.worksId,
        parentId: parent.id,
        content: this.currentContent,
        rootId: rootComment.id,
      }).then(res => {
        if (res.flag) {
          rootComment.childComment.unshift({
            id: res.data.id,
            createTime: res.data.createTime,
            parentNickName: parent.nickName,
            content: this.currentContent,
            userId: this.mineId,
            headImage: this.mineHeadImage,
            parentUserId: parent.userId,
          })
          ElMessage({
            message: res.msg,
            grouping: true,
            type: 'success',
            duration: 2000,
          })
          this.commentCount += 1;
          this.currentContent = "";
        }
      })
    },
    //回复弹出输入框
    async dialogInput (parent, rootComment) {
      ElMessageBox.prompt('', '@' + parent.nickName + ":", {
        confirmButtonText: '回复',
        cancelButtonText: '取消',
        inputPattern:
          /[\s\S]{1,255}$/,
        inputErrorMessage: '1-255个字符',
      })
        .then(({ value }) => {
          this.currentContent = value;
          this.addChildComment(parent, rootComment);
          return true;
        })
        .catch(() => {
          return false;
        })
    },
    //收藏
    addCollection () {
      this.$axios.post("/collection", {
        "worksId": this.works.id,
        "worksTitle": this.works.title,
        "worksFImg": this.works.fimg
      }).then(res => {
        if (res.flag) {
          ElMessage({
            message: res.msg,
            type: 'success',
            duration: 2000,
          });
          this.collection = res.data;
        }
      })
    },
    //是否收藏
    isCollectionFun () {
      this.$axios("/collection/iscollection/" + this.worksId).then(res => {
        if (res.flag) {
          console.log(res);
          this.collection = res.data;
        }
      })
    },
    //获取数量
    getCommentsCount () {
      this.$axios.get("/comment/count/" + this.worksId).then(res => {
        if (res.flag) {
          this.commentCount = parseInt(res.data);
        }
      })
    },
    //切换图片
    swipeChange (index) {
      this.currentImg = index;
      this.swipeIndexChange(index);
    },
    //切换索引改变样式
    swipeIndexChange (index) {
      for (var key in this.$refs.swipeIndex) {
        this.$refs.swipeIndex[key].id = "";
      }
      this.$refs.swipeIndex[index].id = "swipe-index-active";
    },
    //展示图片预览
    showPreview () {
      this.show = true;
      ImagePreview({
        images: this.imgListPreView,
        startPosition: this.currentImg,
        onChange: this.swipeChange11,
      }
      );
    },
    swipeChange11 (index) {
      this.currentImg = index;
      this.$refs.swipe.swipeTo(index);
    },
    //分享选择
    onShareSelect (option) {
      console.log(option);
      this.showShare = false;
      this.copylink();
      ElMessage({
        message: "已复制作品链接,请到" + option.name + "中打开",
        grouping: true,
        type: 'success',
        duration: 2000,
      })
    },
    //更多选择
    onMoreOption (option) {
      console.log(option);
      if (option.name == "分享") {
        this.showShare = true;
      }
      if (option.name == "举报") {
        this.$router.push("/report");
      }
      if (option.name == "删除") {
        ElMessageBox.confirm(
          '确定要删除此作品吗?',
          '',
          {
            confirmButtonText: '确认',
            cancelButtonText: '再想想',
            type: 'warning',
          }
        )
          .then(() => {
            this.$axios.delete("/works/" + this.worksId).then((res) => {
              if (res.flag) {
                ElMessage({
                  message: res.msg,
                  grouping: true,
                  type: 'success',
                  duration: 2000,
                })
                this.$router.back();
              }
            })
          })
          .catch(() => {

          });
      }
      this.moreOption = false;
    },
    //添加粉丝
    addFan () {
      this.$axios.post("/fan/" + this.user.id).then((res) => {
        if (res.flag) {
          this.isFan = true;
          ElMessage({
            message: res.msg,
            grouping: true,
            type: 'success',
            duration: 2000,
          })
        }
      })
    },
    //删除粉丝
    deleteFan () {
      ElMessageBox.confirm(
        '确定要取关吗?',
        '取消关注',
        {
          confirmButtonText: '确认',
          cancelButtonText: '舍不得',
          type: 'warning',
        }
      )
        .then(() => {
          //取消
          this.$axios.delete("/fan/" + this.user.id).then((res) => {
            if (res.flag) {
              this.isFan = false;
              ElMessage({
                message: res.msg,
                grouping: true,
                type: 'success',
                duration: 2000,
              })
            }
          })
        })
        .catch(() => {
        });
    },
    likeClike (workId) {
      this.$axios.post("/like/" + workId + "/1").then(res => {
        if (res.flag) {
          this.like.isLike = true;
          this.like.likeCount += 1;
        }
      })
    },
    cancelLike (workId) {
      this.$axios.delete("/like/" + workId + "/1").then(res => {
        if (res.flag) {
          this.like.isLike = false;
          this.like.likeCount -= 1;
        }
      })
    },
    //如果是自己就加入下架作品操作
    addDeleteOption () {
      if (this.mineId == this.user.id) {
        this.moreOptions[0].push({ name: '删除', icon: deleteImage })
      }
    },
    likeFormat1 (num) {
      return likeFormat(num);
    },
    dateFormat1 (date) {
      return dateFormat(date, 4);
    },
    //复制作品链接
    copylink () {
      var link = window.location.href;
      copyText(document.getElementById('copylink'), link);
    },
    toUserInfo (userId) {
      this.$router.push('/user/info/' + userId);
    }
  },
};
</script>

<style scoped>
.container {
  position: relative;
}
.title-mobile-container {
  width: 100%;
  height: 40px;

  line-height: 40px;
}
.title-mobile-container > .head {
  float: left;
  margin-top: 3px;
  margin-left: 40px;
}
.title-mobile-container > .username {
  width: 150px;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  text-align: left;
  margin-left: 10px;
  font-size: 18px;
  float: left;
}
.title-mobile-container > .share,
.title-mobile-container > .guanzhu {
  float: right;
}
.title-mobile-container .share-btn {
  margin-bottom: 3px;
}
.center {
  padding: 0px 10px 0px 10px;
}
.my-swipe {
  position: relative;
  color: #fff;
  height: 70vh;
  /* background-color: #39a9ed; */
}
.my-swipe-inner {
  height: 100%;
  width: 100%;
}
.swipe-index {
  width: 100%;
  height: 10px;
  text-align: center;
}
.swipe-index > div {
  margin: 0px 1px 0px 1px;
  width: 10px;
  height: 3px;
  display: inline-block;
  background: var(--primary);
}
#swipe-index-active {
  background: var(--active);
}
.custom-indicator {
  position: absolute;
  right: 5px;
  top: 5px;
  padding: 2px 5px;
  font-size: 12px;
  background: rgba(0, 0, 0, 0.1);
  border-radius: 10px;
}
.image {
  width: 100%;
  height: 100%;
}
.works-title {
  margin-top: 10px;
  font-size: 20px;
  font-weight: bold;
}
.works-description {
}
.works-description >>> .el-textarea__inner {
  padding: 0px;
  border: none;
  border-radius: none;
  box-shadow: none;
  font-size: 16px;
}
.works-time {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.3);
  border-bottom: 1px solid rgba(0, 0, 0, 0.2);
  padding-bottom: 10px;
  margin-top: 10px;
  margin-bottom: 10px;
}
.works-tag {
  color: #7171c1;
  cursor: pointer;
}
.commnet-text {
  height: 40px;
  line-height: 40px;
  margin-bottom: 10px;
}
.comment-time {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.3);
}
.commnet-line {
  border-bottom: 1px solid rgba(0, 0, 0, 0.2);
  margin-bottom: 5px;
}
.bottom {
  position: fixed;
  bottom: -10px;
  width: 100%;
  height: 50px;
  background-color: var(--primary);
  z-index: 100;
}
.bottom-input {
  margin-top: 5px;
  float: right;
  width: 50%;
  margin-left: 10px;
}
.bottom-like,
.bottom-input,
.bottom-collection {
  float: right;
  margin-top: 4px;
  margin-right: 10px;
}
.bottom-like-text {
  float: right;
  display: block;
  margin-top: 8px;
}
.child-more {
  width: 100%;
  text-align: left;
  color: #7171c1;
  margin-bottom: 5px;
}
.no-more {
  margin-top: 10px;
  width: 100%;
  text-align: center;
  color: gray;
}
.copy-link {
}
</style>